package com.service.impl;

import com.dao.InventoryDao;
import com.model.Inventory;
import com.service.InventoryService;
import io.seata.core.context.RootContext;
import io.seata.core.model.BranchType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

/**
 * @description:
 * @author: sksun2
 * @create: 2023-07-24
 */
@Service
public class InventoryServiceImpl implements InventoryService {

    @Autowired
    private InventoryDao inventoryDao;

    @Override
    public void adjust(String itemId, Integer num) {
        final String xid = RootContext.getXID();
        final BranchType branchType = RootContext.getBranchType();
        System.out.println("事务xid："+xid + "分支："+branchType.name());

        Inventory inventory = inventoryDao.findByItemId(itemId);

        if(inventory.getInventory() < num){
            throw new RuntimeException("库存不足");
        }
        inventory.setInventory(inventory.getInventory() - num);

        inventoryDao.save(inventory);

    }
}
